package com.ctrip.coverage.service.impl;

import java.io.IOException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import sun.misc.BASE64Encoder;

import com.ctrip.coverage.service.HttpClientService;
@Component
public class HttpClientServiceImpl implements HttpClientService {

	public void requestGet(String urlWithParams) {
		CloseableHttpClient httpclient = HttpClientBuilder.create().build();
		try {
			//HttpGet httpget = new HttpGet("http://www.baidu.com/");  
			HttpGet httpget = new HttpGet(urlWithParams);

			//配置请求的超时设置  
			RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(50).setConnectTimeout(50).setSocketTimeout(50).build();
			httpget.setConfig(requestConfig);

			CloseableHttpResponse response;

			response = httpclient.execute(httpget);

			System.out.println("StatusCode -> " + response.getStatusLine().getStatusCode());

			HttpEntity entity = response.getEntity();
			String jsonStr = EntityUtils.toString(entity);//, "utf-8");  
			System.out.println(jsonStr);

			httpget.releaseConnection();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void requestPost(String url, List<NameValuePair> params) {
		CloseableHttpClient httpclient = HttpClientBuilder.create().build();

		HttpPost httppost = new HttpPost(url);
		try {
			httppost.setEntity(new UrlEncodedFormEntity(params));

			String aa = "admin" + ":" + "admin";
			BASE64Encoder encode = new BASE64Encoder();
			String base64 = encode.encode(aa.getBytes());

			System.out.println(httppost.getRequestLine());

			httppost.setHeader("Authorization", "Basic " + base64);
			CloseableHttpResponse response = httpclient.execute(httppost);
			System.out.println(response.toString());

			HttpEntity entity = response.getEntity();
			String jsonStr = EntityUtils.toString(entity, "utf-8");
			System.out.println(jsonStr);

			httppost.releaseConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
